// Need to use the React-specific entry point to import createApi
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
import { HttpResponse, Wallpaper, WallpaperQuality, WallpapersParams } from '@interfaces';
import { baseURL } from '@config';
import { serialize } from '@helpers';
const prefix = `/api/`;

// Define a service using a base URL and expected endpoints
export const wallpaperApi = createApi({
  reducerPath: 'wallpaper',
  baseQuery: fetchBaseQuery({ baseUrl: `${baseURL}${prefix}` }),
  endpoints: (builder) => ({
    getWallpapers: builder.query<HttpResponse, WallpapersParams>({
      query: params => `wallpaper${serialize(params)}`,
    }),
    getWallpaperByName: builder.query<HttpResponse, { name: string; quality: WallpaperQuality }>({
      query: (params) => `wallpaper/findone${serialize(params)}`,
    })
  }),
})

// Export hooks for usage in functional components, which are
// auto-generated based on the defined endpoints
export const { useGetWallpapersQuery, endpoints } = wallpaperApi

export const getWallpaperByName = (name?: string, quality?: string): Promise<Wallpaper> => {
  return fetch(`${baseURL}${prefix}wallpaper/findone?name=${name}&quality=${quality}`).then(res => res.json()).then(res => res.data);
};
